import { Client } from '../lib/client.js';

class WebSocketClient {
	constructor(opts = {}) {
		this.client = null;
		this.sid = null; // 会话id

		this.init(opts);
	}

	init(opts) {
		const url = opts.url || 'ws://121.41.20.11:8081';

		this.client = new Client(url, {
			onopen: (event) => {
				// 连接成功后初始会话
				this.initSession()
			},
			onclose: (event) => {

			},
			onerror: (event) => {

			}
		});
	}
	// 初始化会话
	initSession() {
		this.send('/v1/session/start', {
			device: 'pc',
			os: 'linux',
			os_version: '3.6',
			app: 'electron-client',
			app_version: '1.0',
			tag: {}
		}, (data) => {
			this.sid = data.value;
			this.client.setRequestProperty('sid', data.value);
		})
	}

	/**
	 * 发送消息
	 * @param {String} method 方法
	 * @param {Object} params 参数
	 * @param {Function} onSuccess 消息发送成功的回调函数
	 * @param {Function} onError 消息失败的回调函数
	 * @param {Function} onEnd 消息发送结束的回调函数
	 */
	send(method, params = {}, onSuccess, onError, onEnd) {
		this.client.asyncSend(method, params, {
			onSuccess,
			onError,
			onEnd
		});
	}

	/**
	 * 消息监听
	 * @param {String} method
	 * @param {Function} cb 回调函数
	 */
	on(method, cb) {
		this.client.addMessageListener(method, cb);
	}
}


if (typeof window != 'undefined') {
	window.WebSocketClient = WebSocketClient;
}

export default WebSocketClient;
